﻿namespace LeetCodeProject._0001_1000._001_100._41_50._041;

public class Solution
{
    public int FirstMissingPositive(int[] nums)
    {
        if (nums == null || nums.Length == 0)
            return 1;
        for (int i = 0; i < nums.Length; i++)
        {
            var ni = nums[i];
            if (ni <= 0 || ni > nums.Length)
                continue;
            while (nums[ni - 1] != ni)
            {
                var tmp = nums[ni - 1];
                nums[ni - 1] = ni;
                ni = tmp;
                if (ni <= 0 || ni > nums.Length)
                    break;
            }
        }

        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] != i + 1)
                return i + 1;
        }

        return nums.Length + 1;
    }
}